﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Slam.Internal;

namespace Slam
{
    public class TypeContainer
    {
        private ITypeContainer _innerContainer;
        private ITypeContainerBuilder _innerContainerBuilder;
        private static string _innerContainerInstanceName; 
        private static string _innerContainerBuilderInstanceName;

        public TypeContainer(SPList list)
        {
            _innerContainerBuilder = Type.GetType(_innerContainerBuilderInstanceName).CreateInstance<ITypeContainerBuilder>();
            _innerContainer = _innerContainerBuilder.Build(list);
        }

        public TypeContainer(SPContentType contentType)
        {
            _innerContainerBuilder = Type.GetType(_innerContainerBuilderInstanceName).CreateInstance<ITypeContainerBuilder>();
            _innerContainer = _innerContainerBuilder.Build(contentType);
        }

        public T Resolve<T>()
        {
            return _innerContainer.Resolve<T>();
        }

        static TypeContainer()
        {
            if (String.IsNullOrEmpty(_innerContainerInstanceName) || String.IsNullOrEmpty(_innerContainerInstanceName))
            {
                Type iTypeContainerType = typeof(ITypeContainer);
                Type iTypeContainerBuilderType = typeof(ITypeContainerBuilder);
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (String.IsNullOrEmpty(_innerContainerInstanceName))
                    {
                        var containerType = assembly.GetTypes().Where(t => iTypeContainerType.IsAssignableFrom(t)).FirstOrDefault();
                        if (containerType != null)
                        {
                            _innerContainerInstanceName = containerType.AssemblyQualifiedName;
                        }
                    }
                    if (String.IsNullOrEmpty(_innerContainerInstanceName))
                    {
                        var containerBuilderType = assembly.GetTypes().Where(t => iTypeContainerBuilderType.IsAssignableFrom(t)).FirstOrDefault();
                        if (containerBuilderType != null)
                        {
                            _innerContainerBuilderInstanceName = containerBuilderType.AssemblyQualifiedName;
                        }
                    }

                    if (!String.IsNullOrEmpty(_innerContainerInstanceName) && !String.IsNullOrEmpty(_innerContainerInstanceName))
                        break;
                }
            }
        }
    }
}
